<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-03 15:18:02
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Market;


use App\Http\Services\Service;

use App\Repositories\CustomerStorageDetailsRepository;
use App\Repositories\CustomerStorageInspectPackRepository;
use App\Repositories\CustomerStorageInspectRepository;
use App\Repositories\CustomerStorageRepository;
use App\Repositories\CustomerStorageStyleRepository;
use App\Repositories\OpenCardDetailsRepository;
use Illuminate\Database\Eloquent\Collection;
/**
 * Summary of StorageService
 * @property CustomerStorageRepository $repository
 * @property CustomerStorageDetailsRepository $details
 * @property CustomerStorageInspectPackRepository $pack
 * @property CustomerStorageInspectRepository $inspect
 * @property OpenCardDetailsRepository $open_card
 * @property CustomerStorageStyleRepository $style
 * @author sunkaiyuan
 */
class StorageService extends Service
    {
    public function boot(
        CustomerStorageRepository $repository,
        CustomerStorageDetailsRepository $details,
        CustomerStorageInspectPackRepository $pack,
        CustomerStorageInspectRepository $inspect,
        OpenCardDetailsRepository $open_card,
        CustomerStorageStyleRepository $style
    ) {
        $this->repository = $repository;
        $this->details    = $details;
        $this->pack       = $pack;
        $this->inspect    = $inspect;
        $this->open_card  = $open_card;
        $this->style      = $style;
        }

    /**
    * 根据ids获取明细列表
    * 用于修改标签
    */
    public function barcode()
    {
        $request = request();
        if ($request->has("ids")) {
            $ids = $request->ids;
            if (!is_array($ids)) {
                $ids = explode(",", $ids);
                }
            $rows = $this->details->whereIn("id", $ids)->with(['inside_barcode', 'outside_barcode'])
            ->select('id', 'dyelot', 'inside_barcode_id', 'outside_barcode_id')->get();
            return $rows;
        }

        return [];
    }

    public function saveBarcode(): void
    {
        $request = request();
        if($request->has('barcodes')){
            $data = $request->barcodes;
            foreach ($data as $value) {
                $this->details->autosave([
                    'id' => $value['id'],
                    'inside_barcode_id' => $value['inside_barcode_id'],
                    'outside_barcode_id' => $value['outside_barcode_id'],
                ]);
            }
        }
    }

    public function getStyle()
        {
        return $this->style->condition()->getGrid();
        }
    protected function saveStyle() : void
        {
        $request = request();
        if ($request->has("ids")) {

            array_filter($request->ids ?? [], function ($id) use ($request)
                {
                $this->details->autosave([
                    'id'             => $id,
                    'customer_style' => array_map(function ($style)
                        {
                        $style['fect_quantity'] = $style['fect_quantity'] ?? 0;
                        if (isEmpty($style['styletext'])) {
                            fail("款号不能为空！");
                            }
                        if (isEmpty($style['quantity'])) {
                            fail("米数不能为空！！");
                            }
                        return $style;
                        }, $request->customer_style),
                ], false, 'customer_style');
                });
            }
        else {
            $this->repository->autosave($request->main);
            // $old_detail_m = $this->details->whereId($request->id)->first();
            // if (isNotEmpty($request->cust_order) && $old_detail_m != $request->cust_order) {
            //     if ($old_detail_m->pro_quantity > 0) {
            //         fail("亲，检验单已成品检验打了标签，不可以修改订单号哦！");
            //         }
            //     if ($old_detail_m->fect_quantity > 0) {
            //         fail("亲，检验单已初检打了标签，不可以修改订单号哦！");
            //         }
            //     }

            $v = $this->details->autosave([
                'id'                  => $request->id,
                'custno'              => $request->custno,
                'color_name'          => $request->color_name,
                'dyelot'              => $request->dyelot,

                'film_category_id'    => $request->film_category_id,
                'material_batch'      => $request->material_batch,
                'material_comp'       => $request->material_comp,
                'backing_category_id' => $request->backing_category_id,
                'cust_order'          => $request->cust_order ?? "",

                'lotname'             => $request->lotname,
                'width'               => $request->width,
                'materialcf'          => $request->materialcf,
                'selfremark'          => $request->selfremark,
                'remark'              => $request->remark,
                'weight'              => $request->weight,
                'customer_style'      => array_map(function ($style)
                    {
                    $style['fect_quantity'] = $style['fect_quantity'] ?? 0;
                    return $style;
                    }, $request->customer_style),
                'label_material'      => $request->label_material,
                'label_color'         => $request->label_color,
                'craft_category_id'   => $request->craft_category_id,
            ], false, 'customer_style');

            $newremark    = "";
            $craft_remark = "";
            $water_remark = "";
            if ($v->craft_category)
                $craft_remark .= $v->craft_category->name . " ";
            if (isNotEmpty($v->material_comp))
                $craft_remark .= $v->material_comp . " ";
            if (isNotEmpty($v->material_batch))
                $craft_remark .= $v->material_batch . " ";
            if ($v->film_category)
                $craft_remark .= $v->film_category->name . " ";
            if ($v->backing_category) {
                $craft_remark .= $v->backing_category->name . $v->backing_category_color . " ";

                }
            if (isNotEmpty(trim($v->water_pressure))) {
                $water_remark .= $v->water_pressure;
                }
            if (isNotEmpty(trim($v->soak))) {
                if (isNotEmpty($water_remark)) {
                    $water_remark = $water_remark . "/" . $v->soak;
                    }
                else {
                    $water_remark .= $v->soak;
                    }
                }

            if (isNotEmpty(trim($v->main->inspection_requirements))) {
                $newremark .= " 正面：" . $v->main->inspection_requirements;
                }
            $v->newremark    = $newremark . $v->printremark . $v->main->remark;
            $v->water_remark = $water_remark;
            if ($v->open_card->count() == 0) {
                $v->craft_remark = $craft_remark;

                }
            $v->save();
            $v->all_inspect->filter(function ($vv) use ($v)
                {
                $vv->cust_order = $v->cust_order;
                $vv->save();
                });
            $v->open_card->filter(function ($vv) use ($v)
                {
                $vv->cust_order   = $v->cust_order;
                $vv->newremark    = $v->newremark;
                $vv->water_remark = $v->water_remark;
                $vv->remark       = $v->remark;
                $vv->save();
                });
            }
        }
    public function list()
        {
        $data = $this->details->condition()->getGrid();
        return $data;
        }

    protected function set_instorage()
        {
        $this->details->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->self_instorage_status_id != 0) {
                fail("单据{$v->self_instorage_status->name}！");
                }
            $v['self_instorage_status_id'] = 1;
            $v->save();
            });
        }
    protected function noset_instorage()
        {
        $this->details->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->self_instorage_status_id != 1) {
                fail("单据{$v->self_instorage_status->name}！");
                }
            $v['self_instorage_status_id'] = 0;
            $v->save();
            });
        }

    protected function repirq()
        {
        $this->details->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            $v->updateQuantity();
            });
        }
    protected function syncproquantity()
        {
        $list = $this->details->condition()->get();
        $list->filter(function ($v)
            {
            $v->lack_quantity = $v->quantity - $v->open_card->sum("quantity");
            $v->save();
            });
        }
    protected function syncnewremark()
        {
        $this->repository->getList()->filter(function ($res)
            {
            $res->details->filter(function ($v) use ($res)
                {
                $newremark    = "";
                $water_remark = "";

                if (isNotEmpty(trim($v->water_pressure))) {
                    if (isNotEmpty(trim($water_remark))) {
                        $water_remark = $water_remark . "/" . $v->water_pressure;
                        }
                    else {
                        $water_remark .= $v->water_pressure;
                        }
                    }

                if (isNotEmpty(trim($res->inspection_requirements))) {
                    $newremark .= " 正面：" . $res->inspection_requirements;
                    }
                $v->newremark    = $newremark . $v->printremark . $res->remark;
                $v->water_remark = $water_remark;

                $v->open_card->filter(function ($vv) use ($v)
                    {
                    $vv->newremark    = $v->newremark;
                    $vv->water_remark = $v->water_remark;
                    $vv->save();
                    });
                $v->save();
                });
            });
        }
    protected function save($request)
        {
        $data               = $request->toArray();
        $data['iscustomer'] = 1;
        if (!is_array($data['details']) || count($data['details']) == 0) {
            fail("明细不能为空！");
            }
        
        foreach ($data['details'] as $key => &$v) {
            $k = $key + 1;
            if (strlen(trim($v['weight'])) > 0) {
                if (!is_numeric(trim($v['weight']))) {
                    fail("第{$k}行错误，克重必须是数字！");
                }
                $v['weight'] = (int)trim($v['weight']);
            } else {
                $v['weight'] = null;
            }
            }    

        $res = $this->repository->autosave($data);
        if ($res->status_id == 1) {
            fail("已审核。禁止编辑！");
            }
        $count = 1;
        $res->details->filter(function ($v) use ($res, &$count)
            {
            $newremark    = "";
            $craft_remark = "";
            $water_remark = "";
            if ($v->craft_category)
                $craft_remark .= $v->craft_category->name . " ";
            if (isNotEmpty($v->material_comp))
                $craft_remark .= $v->material_comp . " ";
            if (isNotEmpty($v->material_batch))
                $craft_remark .= $v->material_batch . " ";
            if ($v->film_category)
                $craft_remark .= $v->film_category->name . " ";
            if ($v->backing_category)
                $craft_remark .= $v->backing_category->name . $v->backing_category_color . " ";
            $craft_remark .= $res->customer_material == 1 ? "(客供)" : "";

            if (isNotEmpty(trim($v->water_pressure))) {
                $water_remark .= $v->water_pressure;
                }
            if (isNotEmpty(trim($v->soak))) {
                if (isNotEmpty($water_remark)) {
                    $water_remark = $water_remark . "/" . $v->soak;
                    }
                else {
                    $water_remark .= $v->soak;
                    }
                }

            if (isNotEmpty(trim($res->inspection_requirements))) {
                $newremark .= " 正面：" . $res->inspection_requirements;
                }
            $v->newremark    = $newremark . $v->printremark . $res->remark;
            $v->craft_remark = $craft_remark;
            $v->water_remark = $water_remark;

            $v->code           = $res->code;
            $v->cust_order     = $res->cust_order;
            $v->customer_id    = $res->customer_id;
            $v->linkman_id     = $res->linkman_id;
            $v->salesman_id    = $res->salesman_id;
            $v->employee_id    = $res->employee_id;
            $v->needEndInspect = $res->needEndInspect;//终检
            $v->needInspect    = $res->needInspect; //初检
            $v->is_sample      = $res->is_sample; //打样
            if ($v->is_sample == 1) {
                $v->generateCode('SAMPLECODE', 'sample_code', 'L');
                }
            if (isEmpty($v->label_material))
                $v->label_material = $v->custno;
            if (isEmpty($v->label_color))
                $v->label_color = $v->color_name;
            // if ($v->is_sample == 1 && $v->quantity > 100) {
            //     fail("大于100米的不能是打样！");
            //     }
            // if ($v->is_sample == 0 && $v->quantity <= 100) {
            //     fail("小于100米的不能是大货！");
            //     }

            if (isEmpty($v->craft_category_id) || $v->craft_category_id == 0) {
                fail("加工类别必选");
                }
            if (isEmpty($v->material_id) || $v->material_id == 0) {
                fail("产品必选");
                }
            if (isEmpty($v->quantity) || $v->quantity == 0) {
                fail("数量必填");
                }
            if (isEmpty($v->unit_id) || $v->unit_id == 0) {
                fail("单位必选");
                }
            if (isEmpty($v->material_comp) || $v->material_comp == 0) {
                $v->material_comp = "";
                }
            if (!in_array($v->craft_category_id, [-1, 6])) {
                if (isEmpty($v->material_batch) || $v->material_batch == 0) {
                    fail("膜类别必选");
                    }
                if (isEmpty($v->film_category_id) || $v->film_category_id == 0) {
                    fail("膜颜色必选");
                    }
                }
            else if ($v->craft_category_id == 6) {
                if ($v->is_sample == 1) {
                    fail("小样不允许单打卷");
                    }
                $res->needEndInspect = $v->needEndInspect = 1;
                $res->save();
                }
            $v->lack_quantity     = $v->quantity;
            $v->customer_material = $res->customer_material;//客供底布 
            $v->location_id       = 3254;
            $v->batchno           = $v->code . substr("000" . $count, -2);
            $v->save();
            $count++;
            });

        return $res;
        }

    protected function finish()
        {
        $this->details->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->finish_id != 0) {
                fail("单据{$v->finish->name}！");
                }
            $v['finishor_id'] = auth()->user()?->employee_id;
            $v['finished_at'] = date("Y-m-d H:i:s");
            $v['finish_id']   = 1;
            $v->save();
            });
        }
    protected function nofinish()
        {
        $this->details->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->finish_id != 1) {
                fail("单据{$v->finish->name}！");
                }
            $v['finishor_id'] = 0;
            $v['finished_at'] = null;
            $v['finish_id']   = 0;
            $v->save();
            });
        }
    protected function audit()
        {
        $this->getMain()->filter(function ($main)
            {
            if ($main->status_id != 0) {
                fail("单据{$main->code}{$main->status->name}！");
                }
            auditSave($main);
            $main->details->filter(function ($v)
                {
                $v->mergeWhere([
                    'iscustomer' => 1,
                    'company_id' => $v->customer_id,
                ])->addStorage("客户来货");
                auditSave($v);
                if ($v->needInspect == 1) {
                    CustomerStorageInspectRepository::create($v);
                    }
                });
            });
        }
    protected function noaudit()
        {
        $openids = [0];
        $this->getMain()->filter(function ($main) use (&$openids)
            {
            if ($main->status_id != 1) {
                fail("单据{$main->code}{$main->status->name}！");
                }
            auditSave($main, false);
            $main->details->filter(function ($v) use (&$openids)
                {
                $v->noaddStorage();
                auditSave($v, false);
                if ($v->needInspect == 1) {
                    if ($v->inspect->pack->count() > 0) {
                        fail("初检已检！请清空初检明细!");
                        }
                    CustomerStorageInspectRepository::nocreate($v);
                    }

                if ($v->open_card->count() > 0)
                    fail("已开卡，禁止反审核！");
                });

            });

        // $this->deleteOpenCard($openids);
        }
    // protected function deleteOpenCard($ids = [0])
    //     {
    //     OpenCardRepository::whereIn("id", $ids)->get()->filter(function ($v)
    //         {

    //         if ($v->status_id != 0) {
    //             fail("已审状态无法删除！");
    //             }
    //         $v->details->filter(function ($vv)
    //             {

    //             if ($vv->process_id != 10) {
    //                 fail("流转卡已【{$vv->process->name}】,操作失败！");
    //                 }
    //             //删除刷卡
    //             $vv->process_pass->filter(fn($v) => $v->delete());
    //             //删除虚拟库存
    //             $vv->wip->filter(fn($v) => $v->delete());
    //             // $vv->process_id      = 0;
    //             // $vv->process_pass_id = 0;

    //             $order                = $vv->order;
    //             $order->open_quantity -= $vv->quantity;
    //             $order->lack_quantity = $order->quantity + $order->open_quantity;
    //             $order->save();


    //             $vv->scheduling->filter(function ($vvv)
    //                 {
    //                 $vvv->delete();
    //                 });
    //             $vv->delete();
    //             });
    //         $v->raws->filter(function ($vv)
    //             {
    //             if ($vv->status_id != 0) {
    //                 fail("辅料已出库！禁止删除!");
    //                 }
    //             $vv->delete();
    //             });
    //         $v->delete();
    //         });
    //     }
    public function getMain()
        {
        $ids = $this->details->whereIn("id", $this->getRequestIds())->pluck("main_id");

        return $this->repository->whereIn("id", $ids)->get();
        }
    protected function delete($request)
        {
        $ids = [];
        $this->details->whereIn("id", $this->getRequestIds())->get()->filter(function ($detail) use (&$ids)
            {
            if ($detail->status_id != 0)
                fail("单据【{$detail->code}】【{$detail->status->name}】！删除失败！");
            $ids[$detail['main_id']] = $detail['main_id'];
            //设置订单剩余可入库数量 
            if ($detail->open_quantity > 0) {
                fail("已开卡！删除失败！");
                }
            $detail->delete();
            });
        $newids   = $this->details->whereIn("main_id", $ids)->pluck("main_id");
        $newids[] = 0;
        $data     = $this->repository
            ->whereIn("id", $ids)
            ->whereNotIn("id", $newids)->get();

        $data->filter(function ($storage)
            {
            $storage->delete();
            });
        return $data;

        }
    public function printReport()
        {
        // if (request("name") == '合并' || request("name") == '流转卡3' || request("name") == '单缸') { 
        $list = $this->details->whereIn("id", $this->getRequestIds())->get();
        $xml  = [];

        $list->filter(function ($v) use (&$xml)
            {
            $v->material;
            $v->customer;
            $v->craft_category;
            $v->main;
            $v->creator;
            $v->strip_index;
            $v->inspect;
            $v->washed_index;
            $v->main;
            $v->main->needInspect    = $v->main->needInspect == 1 ? "是" : "否";
            $v->main->needEndInspect = $v->main->needEndInspect == 1 ? "是" : "否";
            $v->is_sample            = $v->is_sample == 1 ? "小样" : "大货";
            $res['code']             = $v->main->code;

            foreach ($v->toArray() as $k => $potitem) {
                $res['talbe_' . $k] = $potitem;
                }
            $xml[] = $res;
            });

        return createReport($xml);
        }
    protected function setRowColor()
        {
        $request      = request();
        $gdata        = $this->details->whereId($request->id)->first();
        $gdata->bgrgb = $request->color;
        return $gdata->save();
        }
    }